package com.vbobot.demo.spring.nacos.client;


import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Optional;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.ReflectionUtils;

/**
 * 这个同时实现在spring restTemplate的Interceptor和okhttp的Interceptor
 */
public final class SupportGetBodyInterceptor implements Interceptor, ClientHttpRequestInterceptor {
    static ThreadLocal<Boolean> NEED_CONVERT = new ThreadLocal<>();
    static ThreadLocal<Request> BE_CONVERT_REQUEST = new ThreadLocal<>();

    private static void changeMethod(Request request, String method) {
        if (request != null) {
            try {
                Field field = Request.class.getDeclaredField("method");
                field.setAccessible(true);
                field.set(request, method);
            } catch (IllegalAccessException | NoSuchFieldException e) {
            }
        }
    }

    static boolean needConvertToGet() {
        return Optional.ofNullable(NEED_CONVERT.get()).orElse(false);
    }

    /**
     * RestTemplate的拦截，先把方法改为post，让okHttp的Request构建成功
     */
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
            throws IOException {
        try {
            changeToPost(request, body);
            return execution.execute(request, body);
        } finally {
            NEED_CONVERT.remove();
        }
    }

    private static void changeToPost(HttpRequest request, byte[] body) {
        if (request.getMethod() == HttpMethod.GET && body.length > 0) {
            try {
                final Field method = ReflectionUtils.findField(request.getClass(), "method");
                method.setAccessible(true);
                method.set(request, HttpMethod.POST);
                NEED_CONVERT.set(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * okhttp的拦截，让实际发送get请求
     */
    @Override
    public Response intercept(Chain chain) throws IOException {
        try {
            final Request request = chain.request();
            if (needConvertToGet()) {
                changeMethod(request, "GET");
                BE_CONVERT_REQUEST.set(request);
            }
            return chain.proceed(request);
        } finally {
            BE_CONVERT_REQUEST.remove();
        }
    }
}